package com.sinosoft.web.easyui.api;

import cn.com.sinux.spring.commons.OrderCollection;
import cn.com.sinux.spring.commons.PropertyCollection;
import cn.com.sinux.spring.json.JsonFilter;
import cn.com.sinux.spring.utils.PageUtils;
import cn.com.sinux.spring.utils.QueryHelper;
import com.sinosoft.hydra.um.LoginUser;
import com.sinosoft.hydra.um.condition.SearchMessageCondition;
import com.sinosoft.hydra.um.condition.SearchReceiveMessageCondition;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.model.Message;
import com.sinosoft.hydra.um.domain.permission.SysUserMember;
import com.sinosoft.hydra.um.domain.permission.TMessage;
import com.sinosoft.hydra.um.domain.permission.TMessageReceiver;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.MessageService;
import com.sinosoft.hydra.um.services.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 张元第创建
 * 消息管理API
 */
@Controller
@RequestMapping("/api/message")
public class SysMessageApi {

    @Autowired
    private MessageService messageService;
    @Autowired
    private SysUserService userService;

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("index")
    @RequiresPermissions("self:message:index")
    public String receivePage() {
        LoggerHelper.logInfo("查询个人收到的消息列表");
        return "hydra_easyui/message/index";
    }

    /**
     * 消息列表
     *
     * @param message 删除消息的集合
     * @return 发送消息
     */
    @RequestMapping(value = "addMessage", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("message:data:add")
    public Object deleteMessages(LoginUser loginUser, TMessage message, SearchReceiveMessageCondition searchReceiveMessageCondition) {
        message.setFromUser(loginUser);
        message.setSenderName(loginUser.getUserName());
        messageService.sendMessage(message, searchReceiveMessageCondition.getUserIds());
        LoggerHelper.logInfo("发送了消息{}", message.getSendTitle());
        return JsonFilter.doPropertyFilter(message, new PropertyCollection()
                .addProperties(TMessage.class, "sendTitle"));
    }

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("postIndex")
    @RequiresPermissions("message:post:list")
    public String sendIndex() {
        LoggerHelper.logInfo("查询个人发出的消息列表");
        return "hydra_easyui/message/post/index";
    }


    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("toAdd")
    @RequiresPermissions("message:data:add")
    public String toAdd(Model model, @RequestParam(value = "replyUser", required = false) String replyUser) {
        model.addAttribute("replyUser", userService.findOne(replyUser));
        return "hydra_easyui/message/addMessage";
    }

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("toRange")
    public String toRange(@RequestParam(value = "messageId", required = true) String messageId, Model model) {
        model.addAttribute("messageId", messageId);
        return "hydra_easyui/message/messageRange";
    }

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("nonReadMessageTotal")
    @ResponseBody
    public Object nonReadMessageTotal(LoginUser loginUser, HttpServletResponse response) {
        return messageService.nonReadMessageTotal(loginUser.getId());
    }

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("nonReadMessages")
    @ResponseBody
    public Object nonReadMessages(LoginUser loginUser) {
        Page<TMessageReceiver> page = messageService.nonReadMessages(loginUser.getId(), PageUtils.buildPageRequest(1, 10,
                new OrderCollection().addOrder(Sort.Direction.DESC, "tMessage.sendedTime")));
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(TMessageReceiver.class, "id", "tMessage")
                .addProperties(SysUserMember.class, "userName", "userHead"));
    }

    /**
     * 消息接收列表页
     *
     * @return 消息接收列表页
     */
    @RequestMapping("toSearch")
    public String search() {
        return "hydra_easyui/message/search";
    }

    /**
     * 消息接收列表搜索
     *
     * @param pageNumber 页码
     * @param pageSize   每页数
     * @param user       当前登录用户
     * @return 接收结果
     */
    @RequestMapping("list")
    @ResponseBody
    public Object list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                       @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize,
                       SearchReceiveMessageCondition searchReceiveMessageCondition,
                       LoginUser user) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize,
                new OrderCollection().addOrder(Sort.Direction.DESC, "readTime")
                        .addOrder(Sort.Direction.DESC, "id"));
        searchReceiveMessageCondition.setReceiver(user.getId());
        searchReceiveMessageCondition.setReceiverType(BaseConstant.MessageSendType.MESSAGE_SEND_TYPE_NOTICE.name());
        Page<TMessageReceiver> page = messageService.findAllMessageReceiver(searchReceiveMessageCondition, pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysUserMember.class, "userName", "id"));
    }

    /**
     * 消息接收列表搜索
     *
     * @param pageNumber 页码
     * @param pageSize   每页数
     * @param messageId  当前登录用户
     * @return 接收结果
     */
    @RequestMapping("messageRange")
    @ResponseBody
    public Object messageReceives(@RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                                  @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize,
                                  @RequestParam(value = "messageId", required = true) String messageId,
                                  SearchReceiveMessageCondition searchReceiveMessageCondition) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize,
                new OrderCollection().addOrder(Sort.Direction.DESC, "readTime")
                        .addOrder(Sort.Direction.DESC, "id"));
        searchReceiveMessageCondition.setMessageId(messageId);
        Page<TMessageReceiver> page = messageService.findAllMessageReceiver(searchReceiveMessageCondition, pageable);
        Set<String> userIds = new HashSet<String>();
        for (TMessageReceiver messageReceiver : page) {
            if (BaseConstant.MessageSendType.MESSAGE_SEND_TYPE_NOTICE.name().equals(messageReceiver.getReceiverType())
                    && StringUtils.isNotBlank(messageReceiver.getReceiver())) {
                userIds.add(messageReceiver.getReceiver());
            }
        }
        if (!userIds.isEmpty()) {
            List<SysUserMember> members = userService.findAll(userIds);
            for (SysUserMember member : members) {
                for (TMessageReceiver messageReceiver : page) {
                    if (BaseConstant.MessageSendType.MESSAGE_SEND_TYPE_NOTICE.name().equals(messageReceiver.getReceiverType())
                            && member.getId().equals(messageReceiver.getReceiver())) {
                        messageReceiver.setReceiver(member.getUserName());
                    }
                }
            }
        }
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(TMessageReceiver.class, "id", "receiverStatus", "receiverType", "receiver"));
    }

    /**
     * 消息列表
     *
     * @param searchMessageCondition 删除消息的集合
     * @return 删除结果
     */
    @RequestMapping(value = "sendList", method = RequestMethod.POST)
    @ResponseBody
    public Object sendList(@RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                           @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize,
                           SearchMessageCondition searchMessageCondition, LoginUser loginUser) {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize,
                new OrderCollection().addOrder(Sort.Direction.DESC, "createTime")
                        .addOrder(Sort.Direction.DESC, "id"));
        searchMessageCondition.setFromUser(loginUser);
        Page<Message> messages = messageService.findMessages(searchMessageCondition, pageable);
        return JsonFilter.doPropertyFilter(messages, new PropertyCollection()
                .addProperties(SysUserMember.class, "userName"));
    }

    /**
     * 修改多个消息接收状态
     *
     * @param searchReceiveMessageCondition 消息集合
     * @return 修改结果
     */
    @RequestMapping(value = "readMessage", method = RequestMethod.POST)
    @ResponseBody
    public Object readMessage(SearchReceiveMessageCondition searchReceiveMessageCondition) {
        messageService.readMessage(searchReceiveMessageCondition.getIds());
        return true;
    }

    /**
     * 批量删除消息
     *
     * @param messageCondition 删除消息条件
     * @return 删除结果
     */
    @RequestMapping(value = "deleteMessages", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteMessages(SearchReceiveMessageCondition messageCondition) {
        List<TMessageReceiver> receivers = messageService.deleteMessageReceivers(messageCondition.getIds());
        List<String> names = QueryHelper.doQueryProperties(receivers, true, new QueryHelper.PropertyReader<TMessageReceiver, String>() {

            public String read(TMessageReceiver tMessageReceiver) {
                return tMessageReceiver.gettMessage().getSendTitle();
            }
        });
        LoggerHelper.logInfo("删除了收到的消息{}", names);
        return true;
    }

}
